/* eslint-disable */
import router from "@/router/router";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import config from '@/config/config'
import auth from '@/utils/auth'
import bus from "@/components/common/bus";
import Layout from "@/components/common/layout";

NProgress.configure({showSpinner: false})

router.onError((error) => {
    console.error("onError:", error)
    const pattern = /Loading.*?failed/g;
    const isChunkLoadFailed = error.message.match(pattern);
    if (isChunkLoadFailed) {
        location.href = config.baseUrlPrefix + router.history.pending.fullPath.substring(1)
    }
})

let isFetching = false
router.beforeEach(async (to, from, next) => {
    try {
        let account = await auth.getAccount()
        let token = auth.getToken()
        if (!account || !account.id || !token) {
            if (to.path.indexOf("login") >= 0 || to.path.indexOf("404") >= 0 || to.path.indexOf("register") >= 0) {
                next()
            } else {
                next('/login');
            }
        }
        //已登录，无菜单，则获取菜单
        else  {
            if (!account.menus || !account.menus.length) {
                if (isFetching === false) {
                    isFetching = true
                    await auth.fetchMenus()
                    
                    let menus = auth.getAccount().menus
                    if (menus.length > 0) {
                        router.addRoute({
                            path: '/',
                            component: Layout,
                            meta: { title: '' },
                            children: menus
                        })

                        await setTimeout(() => { bus.$emit('account_changed') },20)
    
                        if (to.path === "/") {
                            let path = localStorage.getItem("workflow-last-menu")
                            let existed = false
                            for (let i = 0; i < menus.length; i++) {
                                if (menus[i].path === path) {
                                    existed = true;
                                    break;
                                }
                                for (let j = 0; j < menus[i].children.length; j++) {
                                    if (menus[i].children[j].path === path) {
                                        existed = true
                                        break
                                    }
                                }
                                if (existed) { break; }
                            }
                            if (!existed) { path = menus[0].path }
                            next(path && path.length > 1 ? path : '/')
                        } else {
                            next()
                        }
                    } else {
                        auth.setToken()
                        next('/login');
                    }
                    isFetching = false
                }
            }
            //已登录
            else if (to.path.indexOf("login") >= 0 || to.path.indexOf("register") >= 0) {
                next('/sys')
            }
            //已登录，正常
            else {
                next()
            }
        }
    } catch (err) {
        console.error("catchError:", err)
        next('/')
    }
});

router.afterEach((to, from) => {
    const {path, query: fq} = from
    if (to.path && path.indexOf("404") === -1 &&
        to.path.indexOf("login") === -1 &&
        to.path.indexOf("register") === -1) {
        
        //保存最后访问页面
        localStorage.setItem("workflow-last-menu", to.path)
    }

    NProgress.done()
})
